package com.yjhealth.libs.core.core.fragment;

import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.yjhealth.libs.core.R;
import com.yjhealth.libs.core.log.LogUtil;
import com.yjhealth.libs.core.net.utils.NetworkErrorUtil;
import com.yjhealth.libs.core.utils.DataConverUtil;
import com.yjhealth.libs.core.utils.callphone.CallPhoneUtil;
import com.yjhealth.libs.core.utils.location.LocationConfig;
import com.yjhealth.libs.core.utils.location.LocationUtil;
import com.yjhealth.libs.core.view.titlebar.BsoftToolbar;
import com.yjhealth.libs.core.view.titlebar.config.TitleButtonConfig;
import com.yjhealth.libs.core.webinterface.client.CoreClientInterface;
import com.yjhealth.libs.core.webinterface.client.YjhealthCoreWebChromeClient;
import com.yjhealth.libs.core.webinterface.client.YjhealthCoreWebViewClient;
import com.yjhealth.libs.core.webinterface.config.CallPhoneConfig;
import com.yjhealth.libs.core.webinterface.config.EndLoadMoreConfig;
import com.yjhealth.libs.core.webinterface.config.NativeContainerConfig;
import com.yjhealth.libs.core.webinterface.config.WebRefreshConfig;
import com.yjhealth.libs.core.webinterface.js.BsoftJsInterface;
import com.yjhealth.libs.core.webinterface.js.CoreWebInterface;

public abstract class CoreWebFragment extends CoreListFragment implements CoreWebInterface, CoreClientInterface {
    /*Default*/
    private final static int TIME_OUT = 20000;
    /*Util*/
    private Handler handler = new Handler();
    /*Flag*/
    protected boolean needRestore = false;
    /*View*/
    protected WebView yjhealthCoreWebview;

    @Override
    public void onResume() {
        super.onResume();
        if (yjhealthCoreBosftToolbar != null) {
            yjhealthCoreBosftToolbar.setStatusBar();
        }
    }

    @Override
    protected void initToolBar() {
        super.initToolBar();
        //Toolbar
        if (yjhealthCoreToolbar != null) {
            yjhealthCoreToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    back();
                }
            });
        }
    }

    public void back() {
        if (yjhealthCoreWebview != null
                && !isViewReplace()
                && yjhealthCoreWebview.canGoBack()) {
            yjhealthCoreWebview.goBack();
        } else {
            getActivity().onBackPressed();
        }
    }

    @Override
    protected void initLayout() {
        super.initLayout();

        if (yjhealthCoreBosftToolbar != null) {
            yjhealthCoreBosftToolbar.setLisntener(new BsoftToolbar.OnBsoftToolbarLisntener() {
                @Override
                public void onItemClick(TitleButtonConfig config) {
                    titleBtnClick(config);
                }

                @Override
                public void onBack() {
                    back();
                }

                @Override
                public void updateStatusBar() {

                }
            });
        }

        yjhealthCoreWebview = mainView.findViewById(R.id.yjhealthCoreWebview);
        if (yjhealthCoreWebview != null) {
            yjhealthCoreWebview.getSettings().setJavaScriptEnabled(true);
            yjhealthCoreWebview.getSettings().setDomStorageEnabled(true);
            yjhealthCoreWebview.getSettings().setBlockNetworkImage(false);//解决图片不显示
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                yjhealthCoreWebview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            yjhealthCoreWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
            yjhealthCoreWebview.requestFocus();
            yjhealthCoreWebview.setWebChromeClient(new YjhealthCoreWebChromeClient(this));
            yjhealthCoreWebview.setWebViewClient(new YjhealthCoreWebViewClient(this));
        }

        //默认不可用
        setRefreshEnable(false);
        setLoadMoreEnable(false);
    }

    @Override
    protected void onListRefresh() {
        evaluateJavascript(BsoftJsInterface.javascriptBeginRefresh());
    }

    @Override
    protected void onLoadMoreView() {
        evaluateJavascript(BsoftJsInterface.javascriptLoadMoreData());
    }

    @Override
    protected void onRefreshView() {
        if (yjhealthCoreWebview != null) {
            yjhealthCoreWebview.reload();
        }
    }

    @Override
    public void restoreView() {
        super.restoreView();
        //webview情况下，一直为empty
        setEmpty(true);
    }

    protected void initRefresh(WebRefreshConfig config) {
        if (config == null) {
            return;
        }
        setRefreshEnable(config.getHeader() == WebRefreshConfig.ENABLE);
        setLoadMoreEnable(config.getFooter() == WebRefreshConfig.ENABLE);
    }


    public void load(@NonNull String url) {
        if (yjhealthCoreWebview == null) {
            return;
        }
        LogUtil.d("CoreWebActivity;load;url=" + url);
        if (!TextUtils.isEmpty(url)) {
            restoreView();
            yjhealthCoreWebview.loadUrl(url);
        }
    }

    private void viewError(String errorType, String msg) {
        showErrorView(errorType, msg);
    }

    private Runnable timeoutRunnable = new Runnable() {
        @Override
        public void run() {
            if (yjhealthCoreWebview != null
                    && yjhealthCoreWebview.getProgress() < 100) {
                viewError(NetworkErrorUtil.ERROR_TYPE_TIMEOUT, getString(R.string.yjhealth_core_net_error_type_timeout));
            }
        }
    };

    //********************** CoreClientInterface ********************************************
    @Override
    public void onProgressChanged(WebView view, int newProgress) {

    }

    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        return false;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        Uri uri = Uri.parse(url);
        if (uri == null) {
            return false;
        }
        // 表重写此方法明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        needRestore = true;
        handler.removeCallbacks(timeoutRunnable);
        handler.postDelayed(timeoutRunnable, TIME_OUT);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (needRestore) {
            restoreView();
        }
        handler.removeCallbacks(timeoutRunnable);
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        if (errorCode == WebViewClient.ERROR_HOST_LOOKUP || errorCode == WebViewClient.ERROR_CONNECT || errorCode == WebViewClient.ERROR_TIMEOUT) {
            needRestore = false;
            viewError(NetworkErrorUtil.ERROR_TYPE_OFFLINE, getString(R.string.yjhealth_core_net_error_type_offline));
        }
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        handler.proceed();
    }

    //********************** Js - Android ******************
    @Override
    public void setNativeContainer(String json) {
        LogUtil.d("CoreWebFragment;setNativeContainer;json=" + json);
        NativeContainerConfig nativeContainerConfig = DataConverUtil.convertAtoB(json, NativeContainerConfig.class);
        if (nativeContainerConfig != null) {
            if (yjhealthCoreBosftToolbar != null) {
                yjhealthCoreBosftToolbar.setStatusTitle(nativeContainerConfig.getHeader());
            }
            initRefresh(nativeContainerConfig.getRefresh());
        }
    }

    @Override
    public void closeWebView() {
        getActivity().finish();
    }

    @Override
    public void endRefresh() {
        restoreView();
    }

    @Override
    public void endLoadMoreData(String json) {
        EndLoadMoreConfig config = DataConverUtil.convertAtoB(json, EndLoadMoreConfig.class);
        restoreView();
        if (config != null && config.getFinished() == EndLoadMoreConfig.FINISHED) {
            finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void navigateToHospital(String json) {
        LocationConfig config = DataConverUtil.convertAtoB(json, LocationConfig.class);
        LocationUtil.showLocationDialogSearch(activity, config);
    }

    @Override
    public void callPhone(String json) {
        CallPhoneConfig config = DataConverUtil.convertAtoB(json, CallPhoneConfig.class);
        if (config == null) {
            return;
        }
        CallPhoneUtil.diallPhone(activity, config.phoneNo);
    }

    //****************** to JS ***********************
    protected void evaluateJavascript(String script) {
        if (yjhealthCoreWebview == null
                || TextUtils.isEmpty(script)) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            yjhealthCoreWebview.evaluateJavascript(script, null);
        }
    }

    private void titleBtnClick(TitleButtonConfig config) {
        if (config == null) {
            return;
        }

        if (config.processMode == TitleButtonConfig.MODE_WEB) {
            evaluateJavascript(BsoftJsInterface.javascriptTitleBtnClick(config.id));
        }
    }
}
